package com.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.order.feign.StockOpenFeign;
import com.order.mapper.OrderMapper;
import com.order.pojo.Order;
import com.order.pojo.OrderItem;
import com.order.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private  OrderMapper orderMapper;

    @Resource
    private StockOpenFeign stockOpenFeign;

    @Override
    public Order createOrder(Order order) {
        // 计算订单总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (OrderItem item : order.getOrderItems()) {
            totalAmount = totalAmount.add(item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity())));
        }
        order.setOrderAmount(totalAmount);
        // 先扣减库存（调用库存服务）
        for (OrderItem item : order.getOrderItems()) {
            stockOpenFeign.decreaseStock(item.getProductId(), item.getQuantity());
        }
        orderMapper.insert(order);
        return order;
    }

    @Override
    public Order getOrderById(String orderId) {
        return orderMapper.selectById(orderId);
    }

    @Override
    public List<Order> listOrdersByUserId(String userId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return orderMapper.selectList(queryWrapper);
    }

    @Override
    public void updateOrderStatus(String orderId, Integer newStatus) {
        Order order = getOrderById(orderId);
        order.setOrderStatus(newStatus);
        orderMapper.updateById(order);
    }

    @Override
    public void deleteOrder(String orderId) {
        orderMapper.deleteById(orderId);
    }

    @Override
    public boolean payOrder(String orderId) {
        Order order = getOrderById(orderId);
        if (order!= null && order.getOrderStatus() == 0) {  // 假设0代表未支付状态
            // 这里可以调用真正的支付接口（如对接微信支付、支付宝支付等，此处仅模拟）
            // 支付成功后更新订单状态为已支付（假设1代表已支付）
            updateOrderStatus(orderId, 1);
            return true;
        }
        return false;
    }
}